#include<iostream>
#include<unistd.h>
#include<cstdio>
#include <sys/types.h>
#include<cstdlib>
#include<string>
#include<cstring>
#include <sys/wait.h>
using namespace std;

#define N 2
#define NUM 1024

void Writer(int wfd)
{
    int num=0;
    string s="hello,I am a child";
    pid_t self=getpid();

    char buffer[NUM]={0}; //缓冲区

    while(true)
    {
        //构造字符串
        buffer[0]=0;       //字符串清空，告诉读者：我把这个数组当成了字符串
        snprintf(buffer,sizeof(buffer),"%s-%d-%d\n",s.c_str(),self,num++);
        
        //父进程写入数据,其实就是向内存文件写入
        write(wfd,buffer,strlen(buffer));

        sleep(1);
    }
}

void Reader(int rfd)
{
    char buffer[NUM]={0};

    while(true)
    {
        buffer[0]=0;
        //子进程读取数据，向内存文件中读取数据
        ssize_t n=read(rfd,buffer,sizeof(buffer));    //此出不可以使用strlen
        if(n>0)
        {
            buffer[n]=0;    //0='\0'
            cout<<"father get a message["<<getpid()<<"]#"<<buffer<<endl;
        }
        
    }
} 

int main()
{
    int pipefd[N]={0};
    int n=pipe(pipefd);
    if(n<0)     return 1;

    pid_t id=fork();
    if(id<0)    return 2;

    //child:w   parent:r
    if(id==0)
    {
        //child
        close(pipefd[0]);
        //IPC code 通信代码
        Writer(pipefd[1]);
        exit(0);
    }
    //parent
    close(pipefd[1]);
    //IPC code 通信代码
    Reader(pipefd[0]);

    pid_t rid=waitpid(id,nullptr,0);
    if(id<0)    return 3;

    
    return 0;
}
